#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    /*背景图*/
    this->setStyleSheet("#frame{background-image:url(:/new/prefix1/res/pic/background.jpg)}");


    mytime = new QTimer(this);
    connect(mytime,SIGNAL(timeout()),this,SLOT(slot_timeout()));

    /*读取后台粉丝名称文件*/
    QFile nameFile(":/new/prefix1/res/txt/fans_name.txt");
    if(false == nameFile.open(QIODevice::ReadOnly))
    {
        return;
    }

    /*设置编码为GBK，防止中文读取乱码*/
    QTextStream toText(&nameFile);
    toText.setCodec("GBK");

    /*将文件中的粉丝名称添加到name_items容器中*/
    while (!nameFile.atEnd()) {
        QString name = nameFile.readLine();
        name_items << name.replace("\n","");
    }
    nameFile.close();

    /*将抽奖按钮添加到btn_items容器中*/
    btn_items << ui->btn_1 << ui->btn_2 << ui->btn_3 << ui->btn_4;

    /*设置按钮的样式，初始化时先将按钮隐藏*/
    for(int i = 0;i < btn_items.count();i++)
    {
      connect(btn_items[i],SIGNAL(clicked(bool)),this,SLOT(slot_btn_click()));
      btn_items[i]->setStyleSheet("QPushButton{color:rgb(75,152,204);background-color:rgb(255,255,255);border-radius:20px}"
                                  "QPushButton::hover{color:rgb(53,135,202)}");
      btn_items[i]->hide();
    }

    mytime->start(10000);

    ui->label_head->setStyleSheet("color:rgba(255,255,255,100)");
    ui->label_head->setAlignment(Qt::AlignHCenter);
}

void Widget::slot_timeout()
{
    mytime->stop();
    int pos_x;
    int k = 0;
    int arr_pox_x[11] = {20,220,420,620,820,1020,120,320,520,720,920};//粉丝出现的位置（x坐标）

    /*将所有的粉丝名称一个个显示出来*/
    for(int i = 0; i < name_items.count();i++)
    {
        pos_x = arr_pox_x[k++];
        /*实例化自定义的label控件*/
        label_items << new MaskLabel(pos_x,name_items[i],this);
        label_items[i]->show();

        if(k == 6)//如果一行数目有6个ID号，则换行显示
        {
            msleep(1500);
        }else if(k == 11)//如果下一行数目有11-6=5个ID号，则换行显示
        {
            k = 0;
            msleep(1500);
        }
    }

    /*延时15妙等待移动动画结束后，显示抽奖开始抽奖*/
    msleep(15000);
    for(int i = 0;i < btn_items.count();i++)
    {
      btn_items[i]->show();
    }
    ui->label_head->setText("幸运粉丝");
    ui->label_head->setStyleSheet("color:rgba(255,255,255,255)");
}


/*延时函数*/
void Widget::msleep(int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 200);
}


Widget::~Widget()
{
    delete ui;
}

/*抽奖*/
void Widget::slot_btn_click()
{
    QPushButton* btn = qobject_cast<QPushButton*>(sender());//获取发射信号的对象
    QTime randtime;
    randtime = QTime::currentTime();
    qsrand(randtime.msec() + randtime.second() * 1000);//以当前时间为随机数
    int num = qrand()%name_items.count();
    btn->setText(name_items[num]);//显示出抽奖粉丝名称
    btn->setDisabled(true);

}

